package com.john.elasticsearch.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.annotation.PostConstruct;
import java.util.ArrayList;

@Configuration
@PropertySource(value = {"classpath:application-elasticsearch.properties"})
public class ElasticsearchConfig {
    private ArrayList<HttpHost> hostList;

    /**ES引擎服务端口**/
    @Value(value = "${elasticsearch.port}")
    private Integer port;

    /**ES引擎服务地址**/
    @Value(value = "${elasticsearch.ip}")
    private String hosts;

    /** 连接超时时间 */
    @Value("${elasticsearch.connectTimeOut}")
    private Integer connectTimeOut;

    /** 连接超时时间 */
    @Value("${elasticsearch.socketTimeOut}")
    private Integer socketTimeOut;

    /** 获取连接的超时时间 */
    @Value("${elasticsearch.connectionRequestTimeOut}")
    private Integer connectionRequestTimeOut;

    /** 最大连接数 */
    @Value("${elasticsearch.maxConnectNum}")
    private Integer maxConnectNum;

    /** 最大路由连接数 */
    @Value("${elasticsearch.maxConnectPerRoute}")
    private Integer maxConnectPerRoute;

    @PostConstruct
    public void init() {
        hostList = new ArrayList<>();
        String[] hostStrs = hosts.split(",");
        for (String host : hostStrs) {
            // 使用的协议
            String schema = "http";
            hostList.add(new HttpHost(host, port, schema));
        }
    }

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        RestClientBuilder builder = RestClient.builder(hostList.toArray(new HttpHost[0]));
        // 异步httpclient连接延时配置
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(connectTimeOut);
            requestConfigBuilder.setSocketTimeout(socketTimeOut);
            requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);
            return requestConfigBuilder;
        });
        // 异步httpclient连接数配置
        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setMaxConnTotal(maxConnectNum);
            httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
            return httpClientBuilder;
        });
        return new RestHighLevelClient(builder);
    }
}
